<script setup>
import { ref, onMounted } from 'vue'

const activeTab = ref('diet')
const dietRecords = ref([])
const exerciseRecords = ref([])
const sleepRecords = ref([])

// 添加记录相关状态
const showDietModal = ref(false)
const showExerciseModal = ref(false)
const showSleepModal = ref(false)

// 新记录表单数据
const newDietRecord = ref({
  date: '',
  mealType: 'breakfast', // breakfast, lunch, dinner, snack
  foods: '',
  amount: 'normal', // less, normal, more
  note: ''
})

const newExerciseRecord = ref({
  date: '',
  type: '',
  duration: 30,
  intensity: 'medium', // light, medium, high
  note: ''
})

const newSleepRecord = ref({
  date: '',
  bedTime: '',
  wakeTime: '',
  quality: 'normal', // bad, normal, good
  note: ''
})

// 运动类型选项
const exerciseTypes = [
  '步行',
  '跑步',
  '游泳',
  '骑行',
  '瑜伽',
  '太极',
  '健身',
  '球类运动',
  '跳绳',
  '其他'
]

// 饮食类型选项
const mealTypes = [
  { value: 'breakfast', label: '早餐' },
  { value: 'lunch', label: '午餐' },
  { value: 'dinner', label: '晚餐' },
  { value: 'snack', label: '加餐/零食' }
]

// 饮食量选项
const amountOptions = [
  { value: 'less', label: '少量' },
  { value: 'normal', label: '适中' },
  { value: 'more', label: '较多' }
]

// 运动强度选项
const intensityOptions = [
  { value: 'light', label: '轻度' },
  { value: 'medium', label: '中度' },
  { value: 'high', label: '高强度' }
]

// 睡眠质量选项
const qualityOptions = [
  { value: 'bad', label: '较差' },
  { value: 'normal', label: '一般' },
  { value: 'good', label: '良好' }
]

onMounted(() => {
  // 从本地存储加载记录
  dietRecords.value = uni.getStorageSync('dietRecords') || []
  exerciseRecords.value = uni.getStorageSync('exerciseRecords') || []
  sleepRecords.value = uni.getStorageSync('sleepRecords') || []
})

function switchTab(tab) {
  activeTab.value = tab
}

// 打开添加饮食记录弹窗
function openDietModal() {
  // 设置默认日期为当前日期
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  
  newDietRecord.value = {
    date: `${year}-${month}-${day}`,
    mealType: 'breakfast',
    foods: '',
    amount: 'normal',
    note: ''
  }
  
  showDietModal.value = true
}

// 打开添加运动记录弹窗
function openExerciseModal() {
  // 设置默认日期为当前日期
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  
  newExerciseRecord.value = {
    date: `${year}-${month}-${day}`,
    type: '',
    duration: 30,
    intensity: 'medium',
    note: ''
  }
  
  showExerciseModal.value = true
}

// 打开添加睡眠记录弹窗
function openSleepModal() {
  // 设置默认日期为当前日期
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  
  // 设置默认睡眠时间
  newSleepRecord.value = {
    date: `${year}-${month}-${day}`,
    bedTime: '22:30',
    wakeTime: '07:00',
    quality: 'normal',
    note: ''
  }
  
  showSleepModal.value = true
}

// 关闭所有弹窗
function closeAllModals() {
  showDietModal.value = false
  showExerciseModal.value = false
  showSleepModal.value = false
}

// 添加饮食记录
function addDietRecord() {
  if (!newDietRecord.value.foods) {
    uni.showToast({
      title: '请输入食物内容',
      icon: 'none'
    })
    return
  }
  
  // 创建新记录
  const record = {
    id: Date.now(),
    ...newDietRecord.value,
    createdAt: new Date().toISOString()
  }
  
  // 添加到列表
  dietRecords.value.unshift(record)
  
  // 保存到本地存储
  uni.setStorageSync('dietRecords', dietRecords.value)
  
  uni.showToast({
    title: '添加成功',
    icon: 'success'
  })
  
  closeAllModals()
}

// 添加运动记录
function addExerciseRecord() {
  if (!newExerciseRecord.value.type) {
    uni.showToast({
      title: '请选择运动类型',
      icon: 'none'
    })
    return
  }
  
  // 创建新记录
  const record = {
    id: Date.now(),
    ...newExerciseRecord.value,
    createdAt: new Date().toISOString()
  }
  
  // 添加到列表
  exerciseRecords.value.unshift(record)
  
  // 保存到本地存储
  uni.setStorageSync('exerciseRecords', exerciseRecords.value)
  
  uni.showToast({
    title: '添加成功',
    icon: 'success'
  })
  
  closeAllModals()
}

// 添加睡眠记录
function addSleepRecord() {
  // 创建新记录
  const record = {
    id: Date.now(),
    ...newSleepRecord.value,
    createdAt: new Date().toISOString()
  }
  
  // 添加到列表
  sleepRecords.value.unshift(record)
  
  // 保存到本地存储
  uni.setStorageSync('sleepRecords', sleepRecords.value)
  
  uni.showToast({
    title: '添加成功',
    icon: 'success'
  })
  
  closeAllModals()
}

// 删除饮食记录
function deleteDietRecord(id) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条饮食记录吗？',
    success: (res) => {
      if (res.confirm) {
        dietRecords.value = dietRecords.value.filter(item => item.id !== id)
        
        // 更新本地存储
        uni.setStorageSync('dietRecords', dietRecords.value)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 删除运动记录
function deleteExerciseRecord(id) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条运动记录吗？',
    success: (res) => {
      if (res.confirm) {
        exerciseRecords.value = exerciseRecords.value.filter(item => item.id !== id)
        
        // 更新本地存储
        uni.setStorageSync('exerciseRecords', exerciseRecords.value)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 删除睡眠记录
function deleteSleepRecord(id) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条睡眠记录吗？',
    success: (res) => {
      if (res.confirm) {
        sleepRecords.value = sleepRecords.value.filter(item => item.id !== id)
        
        // 更新本地存储
        uni.setStorageSync('sleepRecords', sleepRecords.value)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 获取饮食类型标签
function getMealTypeLabel(type) {
  const option = mealTypes.find(opt => opt.value === type)
  return option ? option.label : ''
}

// 获取饮食量标签
function getAmountLabel(amount) {
  const option = amountOptions.find(opt => opt.value === amount)
  return option ? option.label : ''
}

// 获取运动强度标签
function getIntensityLabel(intensity) {
  const option = intensityOptions.find(opt => opt.value === intensity)
  return option ? option.label : ''
}

// 获取睡眠质量标签
function getQualityLabel(quality) {
  const option = qualityOptions.find(opt => opt.value === quality)
  return option ? option.label : ''
}
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="title">生活习惯记录</view>
      <view class="subtitle">记录您的饮食、运动和作息情况</view>
    </view>
    
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'diet' }"
        @click="switchTab('diet')"
      >
        饮食记录
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'exercise' }"
        @click="switchTab('exercise')"
      >
        运动记录
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'sleep' }"
        @click="switchTab('sleep')"
      >
        作息记录
      </view>
    </view>
    
    <!-- 饮食记录 -->
    <view v-if="activeTab === 'diet'" class="tab-content">
      <view class="action-bar">
        <button class="add-btn" @click="openDietModal">添加饮食记录</button>
      </view>
      
      <view v-if="dietRecords.length === 0" class="empty-state">
        <view class="empty-icon">🍽️</view>
        <view class="empty-text">暂无饮食记录</view>
        <view class="empty-subtext">点击上方按钮添加饮食记录</view>
      </view>
      
      <view v-else class="record-list">
        <view 
          v-for="record in dietRecords" 
          :key="record.id"
          class="record-item"
        >
          <view class="record-header">
            <view class="record-title">{{ getMealTypeLabel(record.mealType) }}</view>
            <view class="record-date">{{ record.date }}</view>
          </view>
          
          <view class="record-content">
            <view class="record-foods">{{ record.foods }}</view>
            <view class="record-amount">食量: {{ getAmountLabel(record.amount) }}</view>
          </view>
          
          <view v-if="record.note" class="record-note">备注: {{ record.note }}</view>
          
          <view class="record-actions">
            <view class="delete-btn" @click="deleteDietRecord(record.id)">删除</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 运动记录 -->
    <view v-if="activeTab === 'exercise'" class="tab-content">
      <view class="action-bar">
        <button class="add-btn" @click="openExerciseModal">添加运动记录</button>
      </view>
      
      <view v-if="exerciseRecords.length === 0" class="empty-state">
        <view class="empty-icon">🏃</view>
        <view class="empty-text">暂无运动记录</view>
        <view class="empty-subtext">点击上方按钮添加运动记录</view>
      </view>
      
      <view v-else class="record-list">
        <view 
          v-for="record in exerciseRecords" 
          :key="record.id"
          class="record-item"
        >
          <view class="record-header">
            <view class="record-title">{{ record.type }}</view>
            <view class="record-date">{{ record.date }}</view>
          </view>
          
          <view class="record-content">
            <view class="record-duration">时长: {{ record.duration }}分钟</view>
            <view class="record-intensity">强度: {{ getIntensityLabel(record.intensity) }}</view>
          </view>
          
          <view v-if="record.note" class="record-note">备注: {{ record.note }}</view>
          
          <view class="record-actions">
            <view class="delete-btn" @click="deleteExerciseRecord(record.id)">删除</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 睡眠记录 -->
    <view v-if="activeTab === 'sleep'" class="tab-content">
      <view class="action-bar">
        <button class="add-btn" @click="openSleepModal">添加睡眠记录</button>
      </view>
      
      <view v-if="sleepRecords.length === 0" class="empty-state">
        <view class="empty-icon">😴</view>
        <view class="empty-text">暂无睡眠记录</view>
        <view class="empty-subtext">点击上方按钮添加睡眠记录</view>
      </view>
      
      <view v-else class="record-list">
        <view 
          v-for="record in sleepRecords" 
          :key="record.id"
          class="record-item"
        >
          <view class="record-header">
            <view class="record-title">睡眠记录</view>
            <view class="record-date">{{ record.date }}</view>
          </view>
          
          <view class="record-content">
            <view class="record-time">入睡时间: {{ record.bedTime }}</view>
            <view class="record-time">起床时间: {{ record.wakeTime }}</view>
            <view class="record-quality">睡眠质量: {{ getQualityLabel(record.quality) }}</view>
          </view>
          
          <view v-if="record.note" class="record-note">备注: {{ record.note }}</view>
          
          <view class="record-actions">
            <view class="delete-btn" @click="deleteSleepRecord(record.id)">删除</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加饮食记录弹窗 -->
    <view v-if="showDietModal" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">添加饮食记录</view>
          <view class="modal-close" @click="closeAllModals">×</view>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">日期</text>
            <picker 
              mode="date" 
              :value="newDietRecord.date"
              @change="e => newDietRecord.date = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newDietRecord.date }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">餐次</text>
            <picker 
              :range="mealTypes.map(item => item.label)" 
              @change="e => newDietRecord.mealType = mealTypes[e.detail.value].value"
              class="picker"
            >
              <view class="picker-value">{{ getMealTypeLabel(newDietRecord.mealType) }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">食物内容</text>
            <textarea 
              class="textarea" 
              v-model="newDietRecord.foods" 
              placeholder="请输入食物内容，如：米饭、蔬菜、肉类等"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">食量</text>
            <view class="option-selector">
              <view 
                v-for="option in amountOptions" 
                :key="option.value"
                :class="['option-item', { active: newDietRecord.amount === option.value }]"
                @click="newDietRecord.amount = option.value"
              >
                {{ option.label }}
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="textarea" 
              v-model="newDietRecord.note" 
              placeholder="添加备注（选填）"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeAllModals">取消</button>
          <button class="confirm-btn" @click="addDietRecord">确认</button>
        </view>
      </view>
    </view>
    
    <!-- 添加运动记录弹窗 -->
    <view v-if="showExerciseModal" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">添加运动记录</view>
          <view class="modal-close" @click="closeAllModals">×</view>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">日期</text>
            <picker 
              mode="date" 
              :value="newExerciseRecord.date"
              @change="e => newExerciseRecord.date = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newExerciseRecord.date }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">运动类型</text>
            <picker 
              :range="exerciseTypes" 
              @change="e => newExerciseRecord.type = exerciseTypes[e.detail.value]"
              class="picker"
            >
              <view class="picker-value">{{ newExerciseRecord.type || '请选择运动类型' }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">运动时长 (分钟)</text>
            <slider 
              :min="5" 
              :max="180" 
              :step="5" 
              :value="newExerciseRecord.duration"
              @change="e => newExerciseRecord.duration = e.detail.value"
              show-value
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">运动强度</text>
            <view class="option-selector">
              <view 
                v-for="option in intensityOptions" 
                :key="option.value"
                :class="['option-item', { active: newExerciseRecord.intensity === option.value }]"
                @click="newExerciseRecord.intensity = option.value"
              >
                {{ option.label }}
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="textarea" 
              v-model="newExerciseRecord.note" 
              placeholder="添加备注（选填）"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeAllModals">取消</button>
          <button class="confirm-btn" @click="addExerciseRecord">确认</button>
        </view>
      </view>
    </view>
    
    <!-- 添加睡眠记录弹窗 -->
    <view v-if="showSleepModal" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">添加睡眠记录</view>
          <view class="modal-close" @click="closeAllModals">×</view>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">日期</text>
            <picker 
              mode="date" 
              :value="newSleepRecord.date"
              @change="e => newSleepRecord.date = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newSleepRecord.date }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">入睡时间</text>
            <picker 
              mode="time" 
              :value="newSleepRecord.bedTime"
              @change="e => newSleepRecord.bedTime = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newSleepRecord.bedTime }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">起床时间</text>
            <picker 
              mode="time" 
              :value="newSleepRecord.wakeTime"
              @change="e => newSleepRecord.wakeTime = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newSleepRecord.wakeTime }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">睡眠质量</text>
            <view class="option-selector">
              <view 
                v-for="option in qualityOptions" 
                :key="option.value"
                :class="['option-item', { active: newSleepRecord.quality === option.value }]"
                @click="newSleepRecord.quality = option.value"
              >
                {{ option.label }}
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="textarea" 
              v-model="newSleepRecord.note" 
              placeholder="添加备注（选填）"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeAllModals">取消</button>
          <button class="confirm-btn" @click="addSleepRecord">确认</button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
  
  .title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.tabs {
  display: flex;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    
    &.active {
      color: #4caf50;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 25%;
        width: 50%;
        height: 4rpx;
        background-color: #4caf50;
        border-radius: 4rpx;
      }
    }
  }
}

.tab-content {
  min-height: 60vh;
}

.action-bar {
  margin-bottom: 30rpx;
  
  .add-btn {
    background-color: #4caf50;
    color: #fff;
    font-size: 28rpx;
    padding: 15rpx 0;
    border-radius: 8rpx;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .empty-subtext {
    font-size: 26rpx;
    color: #999;
  }
}

.record-list {
  .record-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  }
  
  .record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;
    
    .record-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .record-date {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .record-content {
    margin-bottom: 15rpx;
    
    .record-foods, .record-duration, .record-time {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .record-amount, .record-intensity, .record-quality {
      font-size: 26rpx;
      color: #666;
    }
  }
  
  .record-note {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 15rpx;
  }
  
  .record-actions {
    display: flex;
    justify-content: flex-end;
    
    .delete-btn {
      font-size: 26rpx;
      color: #f44336;
      padding: 6rpx 12rpx;
    }
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 90%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
  
  .modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .modal-close {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 25rpx;
  
  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .picker {
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 15rpx;
    font-size: 28rpx;
    
    .picker-value {
      color: #333;
    }
  }
  
  .textarea {
    width: 100%;
    height: 150rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 15rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }
}

.option-selector {
  display: flex;
  
  .option-item {
    flex: 1;
    text-align: center;
    padding: 15rpx 0;
    border: 1px solid #ddd;
    font-size: 28rpx;
    color: #666;
    
    &:first-child {
      border-radius: 8rpx 0 0 8rpx;
    }
    
    &:last-child {
      border-radius: 0 8rpx 8rpx 0;
    }
    
    &.active {
      background-color: #4caf50;
      color: #fff;
      border-color: #4caf50;
    }
  }
}

.modal-footer {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1px solid #eee;
  
  .cancel-btn, .confirm-btn {
    flex: 1;
    margin: 0 10rpx;
    font-size: 28rpx;
    padding: 15rpx 0;
  }
  
  .cancel-btn {
    background-color: #f5f5f5;
    color: #666;
  }
  
  .confirm-btn {
    background-color: #4caf50;
    color: #fff;
  }
}
</style>